package com.hht.tools.touchlib

import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.view.Gravity
import android.view.WindowManager
import com.hht.toolanduilibs.showLog
import com.hht.touchlibs.UserTouchManager

class TouchService : Service() {

    private lateinit var mWindowManager: WindowManager
    private lateinit var mLayoutParams: WindowManager.LayoutParams
    private lateinit var mTouchView: TouchView

    override fun onCreate() {
        super.onCreate()
        initWindowManager()
    }

    private fun initWindowManager() {
        mWindowManager = this.getSystemService(WINDOW_SERVICE) as WindowManager
        mLayoutParams = WindowManager.LayoutParams()
        if (Build.VERSION.SDK_INT >= 26) {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        }
        mLayoutParams.flags =
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
        mLayoutParams.format = PixelFormat.TRANSLUCENT
        mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
        mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        //TODO 一定要以大屏的左上角作为起点(0,0)，不然坐标要转换
        mLayoutParams.gravity = Gravity.TOP or Gravity.LEFT
        mLayoutParams.x = 200
        mLayoutParams.y = 200
        mTouchView = TouchView(this)
        mWindowManager.addView(mTouchView, mLayoutParams)
        mTouchView.setOnTouchMove { x, y ->
            mLayoutParams.x = x
            mLayoutParams.y = y
            mWindowManager.updateViewLayout(mTouchView, mLayoutParams)
        }
        "touchService addView".showLog(2)
    }

    override fun onDestroy() {
        if (mWindowManager != null) {
            mWindowManager.removeView(mTouchView)
        }
        UserTouchManager.onRecoveryTouch()
        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return Binder()
    }

}